package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0.0
 * @program:sky-take-out
 * @author: CaoYuWei
 * @create:2023-02-15 09:59:51
 **/
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 用户下单  分为三部分：order、orderDetail、addressBook
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO userSubmit(OrdersSubmitDTO ordersSubmitDTO) {
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());//获取地址

        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());//当前用户的购物车

        Orders orders = new Orders();//订单
        BeanUtils.copyProperties(ordersSubmitDTO,orders);//将dto数据拷贝至orders
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setUserId(BaseContext.getCurrentId());
        orders.setStatus(Orders.PENDING_PAYMENT);//待支付
        orders.setPayStatus(Orders.UN_PAID);
        orders.setOrderTime(LocalDateTime.now());
        orderMapper.insert(orders);//封装完成之后  进行插入操作（order表）

        List<OrderDetail> orderDetails = new ArrayList<>();//多条订单详情数据（与订单关联的）
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);

        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }

        orderDetailMapper.insertBatch(orderDetails);//订单菜品或套餐批量插入
        shoppingCartMapper.deleteOneCart(BaseContext.getCurrentId());//清理购物车

        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder() //封装返回
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

        return orderSubmitVO;
    }



    /**
     * 查看历史订单
     * @return
     */
    @Override
    public PageResult selectHistoryOrders(int page, int pageSize, Integer status) {
        PageHelper.startPage(page,pageSize); //分页查询
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        Page<Orders> ordersPage = orderMapper.selectHistoryOrders(ordersPageQueryDTO); //订单分页查询
        List<OrderVO> orderVOList = new ArrayList<>(); //展示前端的数据

        for (Orders orders : ordersPage) {
            List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orders.getId()); //订单菜品套餐详情
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders,orderVO);
            orderVO.setOrderDetailList(orderDetails); //数据封装至vo
            orderVOList.add(orderVO); //voList封装到orderVOList
        }

        return new PageResult(ordersPage.getTotal(),orderVOList);
    }

    /**
     * 查看历史订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO selectOrderDetails(Long id) {
        Orders orders = orderMapper.getById(id); //获取菜品id
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(orders.getId()); //拿到list 封装至vo
        orderVO.setOrderDetailList(byOrderId);
        return orderVO;
    }


    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancelOrder(Long id) {
        Orders orderId = orderMapper.getById(id);
        Orders orders = new Orders();
        orders.setId(orderId.getId());
        orders.setStatus(Orders.CANCELLED);//取消状态
        orders.setCancelTime(LocalDateTime.now());//设置关闭时间
        orderMapper.update(orders);
    }

    /**
     * 再来一单（订单详情---->购物车）
     * @param id
     */
    @Override
    public void repetitionOrder(Long id) {
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);//根据id查询订单的详情（菜品和套餐）
        List<ShoppingCart> cartList = new ArrayList<>(); //创建购物车的list

        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            cartList.add(shoppingCart);//一个一个加入购物车
        }
        shoppingCartMapper.insertBatch(cartList);
    }


    /**
     * 客户端订单查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult orderSelect(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());//分页查询
        Page<Orders> page = orderMapper.orderSelect(ordersPageQueryDTO);


        List<OrderVO> orderVOList = new ArrayList<>();
        List<Orders> ordersList = page.getResult();//获取订单集合
        OrderVO orderVO = new OrderVO();
        for (Orders orders : ordersList) {
            //查询订单详情
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
           // List<String> orderDishList =
            for (OrderDetail orderDetail : orderDetailList) {
                String orderDish = orderDetail.getName()+orderDetail.getNumber();
                //orderDetailList.add(orderDish);
            }
        }

        for (Orders orders : ordersList) {
            BeanUtils.copyProperties(orders,orderVO);
        }
        return new PageResult(page.getTotal(),orderVOList);
    }
}